//
//  MTPartyTaskDetailViewController.swift
//  MT
//
//  Created by ooops on 2020/5/26.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import Eureka
import YPNavigationBarTransition
import RxSwift
import Result
import JMessage

extension MTPartyTaskDetailViewController: MTPartyDetailRemarkCellDelegate, MTCancelTaskWarningViewDelegate {
    func didSelectUserAvatar(user: JMSGUser) {
        let c = MineViewController(username: user.username)
        navigationController?.pushViewController(c, animated: true)
    }
    
    func checkInviteInfo(canComm: Bool) {
        if canComm {
            guard let pushId = self.model.detailResult?.pushId else { return }
            JMSGConversation.createGroupConversation(withGroupId: "\(pushId)") { (result, error) in
                if let conv = result as? JMSGConversation {
                    let vc = JCChatViewController(conversation: conv, true)
                    if let baseTabBarViewController = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController) {
                        self.navigationController?.popToRootViewController(animated: false)
                        baseTabBarViewController.selectedIndex = 1
                        if let nav = baseTabBarViewController.selectedViewController as? BaseNavController {
                            DispatchQueue.main.after(0.25) {
                                nav.pushViewController(vc, animated: true)
                            }
                        }
                    }
                }
            }
            return
        }
        let vc = MTPartyInviteInfoViewController()
        vc.partyId = self.model.detailResult?.id
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func cancelPartyTask(view: MTCancelTaskWarningView) {
        view.removeFromSuperview()
        
        guard let partyId = model.detailResult?.id else { return }
        let dic: [String  : Any] = ["partyTaskId" : partyId]
        MTCreateTaskTool.cancelPartyTask(provider: partyProvider, parameters: dic, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            if let m = model, m.code == 200 {
                DispatchQueue.main.async {
                    weakSelf.navigationController?.popToRootViewController(animated: true)
                }
            } else if let msg = model?.message {
                DispatchQueue.main.async {
                    MBProgressHUD_JChat.show(text: msg, view: weakSelf.view, 2)
                }
            }
        }) { (_) in
            
        }
    }
    
}

class MTPartyTaskDetailViewController: BaseFormViewController {
    
    private var model: MTPartyListModel!
    private var isOwner: Bool = false
    /// 详情商业认证 - 由列表传递
    var certification: Bool = false
    
    private lazy var partyProvider: MTProvider<MTCreateTaskAPI> = {
        let provider = MTProvider<MTCreateTaskAPI>()
        return provider
    }()
    
    lazy var rightButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "party_detail_more"), for: .normal)
        btn.setBackgroundImage(UIImage(named: "more_blur"), for: .normal)
        btn.addTarget(self, action: #selector(rightOperate), for: .touchUpInside)
        return btn
    }()
    
    lazy var bgView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.text.x1d1a1a
        v.isHidden = true
        return v
    }()
    
    lazy var joinButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("我要报名", for: .normal)
        btn.addTarget(self, action: #selector(MTPartyTaskDetailViewController.joinTask), for: .touchUpInside)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.backgroundColor = UIColor(hex: 0xffc000)
        btn.layer.cornerRadius = 19.5
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        return btn
    }()
    
    lazy var statusLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(16)
        l.backgroundColor = UIColor(hex: 0xe6e6e6)
        l.textColor = UIColor(hex: 0x8B8B8B)
        l.text = "已报名"
        l.isHidden = true
        l.textAlignment = .center
        return l
    }()
    
    @objc private func rightOperate() {
        // 取消按钮 index = 0
        var otherButtonTitles: [String] = [""]
        if isOwner {
            if model.detailResult?.status == .started {
                self.rightButton.isHidden = true
                return
            }
            otherButtonTitles = ["编辑聚会信息", "邀请好友（俱乐部）加入聚会"]
            canEdit(otherButtonTitles: otherButtonTitles, true)
            return
        }
        if let pushId = model?.detailResult?.pushId {
            JMSGGroup.groupInfo(withGroupId: "\(pushId)") { [weak self] (result, error) in
                guard let weakSelf = self else { return }
                if let g: JMSGGroup = result as? JMSGGroup, error == nil {
                    /// 如果是群主 - 聚会任务发布者
                    if g.owner == JMSGUser.myInfo().username {
                        otherButtonTitles = ["编辑聚会信息", "邀请好友（俱乐部）加入聚会"]
                        weakSelf.canEdit(otherButtonTitles: otherButtonTitles, true)
                        weakSelf.isOwner = true
                    } else {
                        otherButtonTitles = ["邀请好友（俱乐部）加入聚会"]
                        weakSelf.canEdit(otherButtonTitles: otherButtonTitles, false)
                    }
                } else {
                    otherButtonTitles = ["邀请好友（俱乐部）加入聚会"]
                    weakSelf.canEdit(otherButtonTitles: otherButtonTitles)
                }
            }
        } else if model?.detailResult?.userName == JMSGUser.myInfo().username {
            otherButtonTitles = ["编辑聚会信息", "邀请好友（俱乐部）加入聚会"]
            self.canEdit(otherButtonTitles: otherButtonTitles, true)
            self.isOwner = true
        } else {
            otherButtonTitles = ["邀请好友（俱乐部）加入聚会"]
            self.canEdit(otherButtonTitles: otherButtonTitles)
        }
    }
    
    private func canEdit(otherButtonTitles: [String], _ isPublish: Bool = false) {
        let clickedHandler = { [weak self] (sheetView: MTActionSheetView, index: Int) in
            guard let weakSelf = self else { return }
            if index == 0 {
                
                return
            }
            if index == 1 {
                /// 非发布者第一项就是分享
                if !isPublish {
                    weakSelf.forward()
                    return
                }
                if let pushId = weakSelf.model?.detailResult?.pushId {
                    let vc = MTCreatePartyTaskViewController(isEditMode: true, clubId: "\(pushId)") { (flag) in
                        if flag {
                            DispatchQueue.main.async {
                                weakSelf.form.removeAll()
                            }
                            weakSelf.queryPartyDetail()
                        }
                    }
                    
                    DispatchQueue.main.async {
                        weakSelf.navigationController?.pushViewController(vc, animated: true)
                    }
                } else if let partyId = weakSelf.model.detailResult?.id {
                    let vc = MTCreatePartyTaskViewController(isEditMode: true, partyId: "\(partyId)") { (flag) in
                        if flag {
                            DispatchQueue.main.async {
                                weakSelf.form.removeAll()
                            }
                            weakSelf.queryPartyDetail()
                        }
                    }
                    
                    DispatchQueue.main.async {
                        weakSelf.navigationController?.pushViewController(vc, animated: true)
                    }
                }
                return
            }
            if index == 2 {
                /// 飞发布者若有第二项 是取消
                if !isPublish {
                    weakSelf.cancelParty()
                    return
                }
                /// 发布者第二项是转发
                weakSelf.forward()
                return
            } else {
                if !isPublish {
                    weakSelf.cancelParty()
                } else {
                    weakSelf.cancelPartyTask()
                }
            }
        }
        
        var titles = otherButtonTitles
        /// 普通用户申请, 且通过,c 才会有取消参加选项
        if model.detailResult?.status == .accept && !isPublish {
            titles.append("放弃参与聚会")
        }
        
        if model.detailResult?.status == .ownner && isPublish {
            titles.append("取消聚会")
        }
        
        let actionSheet = MTActionSheetView(cancelButtonTitle: nil,
                                          otherButtonTitles: titles,
                                          clickedHandler: clickedHandler)
        actionSheet.canTouchToDismiss = true
//        actionSheet.backgroundColor = UIColor(hex: 0x000000, alpha: 0.6)
        DispatchQueue.main.async {
            actionSheet.show()
        }
    }
    
    private func cancelPartyView() {
        let v: MTCancelTaskWarningView = MTCancelTaskWarningView(frame: view.bounds)
        v.delegate = self
        UIApplication.shared.keyWindow?.addSubview(v)
    }
    
    private func cancelParty() {
        guard let partyId = model.detailResult?.id else { return }
        let dic: [String  : Any] = ["partyId" : partyId, "userName" : JMSGUser.myInfo().username, "type" : 3]
        MTCreateTaskTool.operateInvite(provider: partyProvider, parameters: dic, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            if let m = model, m.code == 200 {
                DispatchQueue.main.async {
                    weakSelf.navigationController?.popToRootViewController(animated: true)
                }
            }
        }) { (_) in
            
        }
    }
    
    private func cancelPartyTask() {
        cancelPartyView()
    }
    
    private func forward() {
        
        let vc = JCForwardViewController()
//        vc.message = message
        vc.model = self.model
        let nav = BaseNavController(rootViewController: vc)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true, completion: {
            
        })
        
//        if let message = conversation.message(withMessageId: message.msgId) {
//            let vc = JCForwardViewController()
//            vc.message = message
//            let nav = BaseNavController(rootViewController: vc)
//            nav.modalPresentationStyle = .fullScreen
//            self.present(nav, animated: true, completion: {
//                self.toolbar.isHidden = true
//            })
//        }
    }
    
    private var taskId: Int?
    /// 聚会任务群传递, 若有此ID优先使用此id 作为入参请求数据, 参数名为 pushId
    var taskPushId: Int?
    
    override func refreshView() {
        queryPartyDetail()
    }
    
//    override func viewWillAppear(_ animated: Bool) {
//        super.viewWillAppear(animated)
//        self.queryPartyDetail()
//    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.backgroundColor = .white
        queryPartyDetail()
        
        view.addSubview(bgView)
        bgView.addSubview(joinButton)
        view.addSubview(statusLabel)
        
        bgView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(50 + ScreenBottomExtraOffset)
        }
        
        joinButton.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview()
            make.centerX.equalToSuperview()
            make.height.equalTo(39)
            make.width.equalTo(266)
            make.bottom.equalToSuperview().offset(-ScreenBottomExtraOffset)
        }
        
        statusLabel.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(49)
        }
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 50, right: 0)
        tableView.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.queryPartyDetail()

        }
    }
    
    convenience init(partyTaskId id: Int) {
        self.init()
        self.taskId = id
    }
    
    @objc private func joinTask() {
        if let pushId = self.model?.detailResult?.id {
            let vc: MTTaskInviteViewController = MTTaskInviteViewController(pushId: "\(pushId)")
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    private func queryPartyDetail() {
        var parameters: [String : Any] = [:]
        if let id = taskId {
            parameters = ["id" : id]
        }
        if taskPushId != nil {
            parameters = ["pushId" : taskPushId!]
        }
        MTCreateTaskTool.queryPartyDetail(provider: partyProvider, parameters: parameters, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            if let m = model, m.code == 200 {
                m.detailResult?.certification = weakSelf.certification
                self?.model = m
                DispatchQueue.main.async {
                    if m.detailResult?.status == .started || m.detailResult?.status == .ended {
                        weakSelf.rightButton.isHidden = true
                    }
                    weakSelf.form.removeAll()
                    weakSelf.setupForm()
                    weakSelf.setValue(value: m, forTag: partyDetailHeader)
                    weakSelf.setValue(value: m, forTag: partyDetailType)
                    weakSelf.setValue(value: m, forTag: partyDetailTimeAddress)
                    weakSelf.setValue(value: m, forTag: partyDetailRemark)
                    
                    /// 已结束的任务不显示相关操作按钮
                    if m.detailResult?.status == .ended {
                        weakSelf.rightButton.isHidden = true
                    }
                    
                    if let pushId = m.detailResult?.pushId {
                        JMSGGroup.groupInfo(withGroupId: "\(pushId)") { [weak self] (result, error) in
                            guard let weakSelf = self else { return }
                            if let g: JMSGGroup = result as? JMSGGroup, error == nil {
                                if g.owner == JMSGUser.myInfo().username {
                                    weakSelf.isOwner = true
                                    DispatchQueue.main.async {
                                        //weakSelf.joinButton.isHidden = true
                                        weakSelf.bgView.isHidden = true
                                        weakSelf.statusLabel.isHidden = true
                                    }
                                } else {
                                    weakSelf.changeView(model: model)
                                }
                            }
                        }
                    } else {
                        weakSelf.changeView(model: model)
                    }
                    
                }
            }
        }) { (_) in
            
        }
    }
    
    private func changeView(model: MTPartyListModel?) {
        if let s: MTPartyListTaskStatusType = model?.detailResult?.status {
            self.bgView.isHidden = true
            self.statusLabel.isHidden = true
            switch s {
            case .wating:
                self.statusLabel.text = "招募中"
                self.statusLabel.isHidden = true
                self.bgView.isHidden = false
            case .started:
                self.statusLabel.text = "进行中"
                self.statusLabel.isHidden = false
                /// 进行中, 无法报名
                self.bgView.isHidden = true
            case .ended:
                self.statusLabel.text = "任务已结束，3天后群将自动解散"
                self.statusLabel.isHidden = false
                self.bgView.isHidden = true
            case .invite:
                self.statusLabel.text = "已申请"
                self.statusLabel.isHidden = false
                self.bgView.isHidden = true
            case .reject:
                self.statusLabel.text = ""
                self.statusLabel.isHidden = true
                self.bgView.isHidden = false
            case .ownner:
                self.statusLabel.isHidden = true
                self.bgView.isHidden = true
            default:
                self.statusLabel.text = "已报名"
                self.statusLabel.isHidden = false
                self.bgView.isHidden = true
            }
        } else {
            self.statusLabel.isHidden = true
            self.bgView.isHidden = false
        }
    }

    private func setupForm() {
                
        let section = Section()
        form +++ section
            <<< MTPartyHeaderRow() { row in
                //row.cell.height = { return 276}
                row.cell.height = { UITableView.automaticDimension }
                row.tag = partyDetailHeader
            }
            <<< MTPartyDetailTRow() { row in
                row.cell.height = { UITableView.automaticDimension }
                row.tag = partyDetailType
            }
            <<< MTPartyDetailTimeRow() { row in
                row.cell.height = { UITableView.automaticDimension }
                row.tag = partyDetailTimeAddress
            }
            <<< MTPartyRemarkRow() { row in
                row.cell.height = { UITableView.automaticDimension }
                row.cell.delegate = self
                row.tag = partyDetailRemark
                row.cell.delegate = self
            }
        
        GroupTableSeparatorFix.removeFirstAndLastSeparatorLine()
        if self.model?.detailResult?.allopatryAllopatryFlag == 1 {
            let v = MTPartyDetailFooterView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 105))
            self.tableView.tableFooterView = v
        }
    }
    
    /// 赋值
    /// - Parameters:
    ///   - value:
    ///   - tag:
    private func setValue(value: MTPartyListModel, forTag tag: String) {
        switch tag {
        case partyDetailHeader:
            if let row: MTPartyHeaderRow = self.form.rowBy(tag: tag) as? MTPartyHeaderRow {
                row.cell.model = value
                row.reload()
                row.cellUpdate { (cell, row) in
                    
                }
            }
        case partyDetailType:
            if let row: MTPartyDetailTRow = self.form.rowBy(tag: tag) as? MTPartyDetailTRow {
                row.cell.model = value
                row.reload()
                row.cellUpdate { (cell, row) in
                    
                }
            }
        case partyDetailTimeAddress:
            if let row: MTPartyDetailTimeRow = self.form.rowBy(tag: tag) as? MTPartyDetailTimeRow {
                row.cell.model = value
                row.reload()
                row.cellUpdate { (cell, row) in
                    
                }
            }
        case partyDetailRemark:
            if let row: MTPartyRemarkRow = self.form.rowBy(tag: tag) as? MTPartyRemarkRow {
                row.cell.model = value
                row.reload()
                row.cellUpdate { (cell, row) in
                    
                }
            }
        default:
            break
        }
    }

}

extension MTPartyTaskDetailViewController {
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 11
    }
    
}

extension MTPartyTaskDetailViewController {
    
    override func yp_navigationBarTintColor() -> UIColor! {
        return .white
    }

    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .backgroundStyleTransparent]
    }
}
